package com.sec.android.app.myfiles.listener;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.support.v4.content.LocalBroadcastManager;
import android.text.TextUtils;

import com.sec.android.app.myfiles.activity.AbsMyFilesActivity;
import com.sec.android.app.myfiles.dialog.AbsDialogFragment;
import com.sec.android.app.myfiles.info.AppConstants;
import com.sec.android.app.myfiles.listener.ListenerMgr.LifeCycle;

public class DialogReceiver extends AbsBroadcastReceiverImp {
    private AbsDialogFragment mDialogFragment;

    public DialogReceiver(Context context, AbsDialogFragment fragment, LifeCycle registerTime, LifeCycle unregisterTime) {
        super(context, registerTime, unregisterTime);
        mDialogFragment = fragment;
    }

    @Override
    IntentFilter getIntentFilter() {
        if (mIntentFilter == null) {
            mIntentFilter = new IntentFilter(AppConstants.DISMISS_DIALOG);
        }
        return mIntentFilter;
    }

    @Override
    BroadcastReceiver getBroadcastReceiver() {
        if (mReceiver == null) {
            mReceiver = new BroadcastReceiver() {
                @Override
                public void onReceive(Context context, Intent intent) {
                    if (intent.getAction().equals(AppConstants.DISMISS_DIALOG)) {
                        if (mDialogFragment != null && mDialogFragment.getDialog() != null && mDialogFragment.getDialog().isShowing()) {
                            AbsMyFilesActivity activity = (AbsMyFilesActivity) mDialogFragment.getActivity();
                            int processId = intent.getIntExtra(AppConstants.EXTRA_PROCESS_ID, -1);
                            String tag = intent.getStringExtra(AppConstants.EXTRA_TAG);
                            if (activity != null && activity.getProcessId() == processId) {
                                if (TextUtils.isEmpty(tag) || mDialogFragment.getTag().equals(tag)) {
                                    mDialogFragment.dismissByBroadcast();
                                }
                            }
                        }
                    }
                }
            };
        }
        return mReceiver;
    }

    @Override
    public void registerListener() {
        LocalBroadcastManager.getInstance(mContext).registerReceiver(mReceiver, mIntentFilter);
    }

    @Override
    public void unregisterListener() {
        LocalBroadcastManager.getInstance(mContext).unregisterReceiver(mReceiver);
        mDialogFragment = null;
    }
}
